<template>
	<eui-page-frame :topHeight="260" :bottomHeight="88">
		<template #top>
			<view class="content-img">
				<eui-navbar ref="EuiNavBar" title="配送收货" color="#000000" backgroundColor="#FFFFFF"
					:storeName="sUserStoreName" :storeId="sUserStore" displayable="true">
				</eui-navbar>
				<view class="top-view">
					<eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品编码、条码、单据号"
						leftIcon="icon-sousuo" :focus="true" @confirm="searchConfirm" @leftIconClick="leftIconClick" 
                        :displayable="mainData.c_status !== '0' || mainData.c_approve_status !== '1'" radius="30">
					</eui-search-bar>
				</view>
			</view>
		</template>
		<eui-page-content>
			<view class="footer-view">
				<eui-card title="基本信息" showTitleLine="true" h-padding="28">
					<template v-slot:extra>
						<view class="extra-view" @click="changeBasicStatus">
							<eui-uicons :type="showBasic ? 'up' : 'down'" size="24" />
						</view>
					</template>
					<view v-if="showBasic">
						<eui-card-input style="padding: 16rpx 0rpx;" v-model="c_id" title="单据号" placeholder="请选择/扫描配送单"
							rightIconType="right" type="text" @iconClick="clickRight('c_id')" displayable="false" />
						<view style="margin-top: 10rpx;">
							<eui-detail-show :items="indexItems" v-model="mainData" size="normal"></eui-detail-show>
							<!-- 	<eui-text v-model="mainData.c_out_store_id" title="配送中心" type="titlename2"
								:name="getRelatedName('rdsStores', mainData.c_out_store_id)" cWidth="width: 100%"
								occupy />
							<eui-text v-model="mainData.c_out_adno"
								:name="getRelatedName('rdsDeparts', mainData.c_out_adno)" type="titlename2" title="部门:"
								cWidth="width: 100%" occupy />
							<eui-text v-model="mainData.c_out_wno" type="titlename2" title="仓库"
								:name="getRelatedName('rdsWnos', mainData.c_out_wno)" cWidth="width: 100%" occupy />
							<eui-text v-model="mainData.c_at_move_out" type="price2" title="金额"
								:valueStyle="showRightStyle" />
							<eui-text v-model="mainData.c_n_out" type="price2" title="总数量(含赠品)"
								:valueStyle="showRightStyle" />
							<eui-text v-model="mainData.c_sku_out" type="price2" title="品种数(含赠品)"
								:valueStyle="showRightStyle" />
							<eui-text v-model="c_n_total" type="price2" title="已收正品数量" :valueStyle="showRightStyle" />
							<eui-text v-model="c_sku_total" type="number2" title="已收品种数" :valueStyle="showRightStyle" />
							<eui-text v-model="c_n_free_total" type="price2" title="已收赠品数量"
								:valueStyle="showRightStyle" /> -->
						</view>
					</view>
				</eui-card>
				<view style="margin-top: 20rpx;">
					<eui-card title="商品信息" h-padding="28">
						<view :ref="'dataItem' + index" v-for="(item, index) in detailData" :key="index"
							@click="onClickGdsInfo(item, index)">
							<view class="item-gds-title">
								<eui-text :value="index + 1 + '. [' + item.c_gcode + ']' + item.c_gname" type="id" />
								<eui-uicons size="32" fontFamily="enjoyIcon5" customPrefix="icon-jiantouxiangyou" />
							</view>
							<eui-detail-show :items="dataGoodsItems" v-model="detailData[index]"
								size="normal"></eui-detail-show>
							<eui-line v-if="index<detailData.length-1"></eui-line>
						</view>
					</eui-card>
				</view>
			</view>
		
		</eui-page-content>
		<template #bottom>
			<view class="bt-button">
				<eui-button type="max2" title="保存" @buttonClick="saveClick"
					:disabled="!['3', '9'].includes(c_status) || mainData.c_d_status != '1'" />
				<eui-button type="max" title="确认收货" @buttonClick="receiptClick"
					:disabled="!['3', '9'].includes(c_status) || mainData.c_d_status != '1'" />
			</view>
		</template>
	</eui-page-frame>
	<eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :mask-click="true">
		<view class="popup-content">
			<view class="popup-title">详情</view>
			<view style="padding-left: 5px;">
				<eui-card :title="'[' + currentGds.c_gcode + ']' + currentGds.c_gname">
					<eui-detail-show :items="popupGoodsItems" v-model="currentGds"
						size="normal"></eui-detail-show>
				</eui-card>
				<!-- <eui-text :value="'[' + currentGds.c_gcode + ']' + currentGds.c_gname" type="name" occupy />
				 -->
				<!-- <view class="m-list-top">
					<eui-text :value="'[' + currentGds.c_gcode + ']' + currentGds.c_gname" type="name" occupy />
					<eui-text :value="currentGds.c_barcode" type="name" title="条码:" />
					<eui-text :value="currentGds.c_move_pack + '/' + currentGds.c_move_unit" type="name"
						title="含量/单位:" />
					<eui-text :value="currentGds.c_n_out" type="price" title="发货数量:" />
					<eui-text :value="currentGds.c_n_free_out" type="price" title="赠品数量:" />
					<eui-text :value="currentGds.c_pt_move_fact" type="price" title="配送价:" />
					<eui-text :value="currentGds.c_at_move_in" type="price" title="配送金额:" />
					<eui-text :value="currentGds.c_n_pack_in" type="price" title="收货件数:" />
					<eui-text :value="currentGds.c_n_odd_in" type="price" title="收货零数:" />
				</view> -->
				<eui-card-input id="c_n_in" v-model="currentGds.c_n_in" title="收货数量" type="number" required
					@confirm="validateDetail" fieldName="c_n_in" isBlur :maxlength="9"  :focus="true"/>
				<eui-card-input id="c_n_free_in" v-model="currentGds.c_n_free_in" title="赠品数量" type="number" required
					@confirm="validateDetail" :maxlength="9"  fieldName="c_n_free_in" isBlur />
			</view>
			<view class="bt-button">
				<eui-button type="max2" title="关闭" @buttonClick="cancelClick" />
				<eui-button type="max" title="确认" @buttonClick="submitClick" />
			</view>
		</view>
	</eui-popup>
</template>

<script setup type="ts">
	import { ref, reactive, onMounted } from 'vue';
	import {useMainStore} from "@/store/modules/store";
	import {useLoginStore} from "@/store/modules/useLoginStore";
	import { validateStores } from '@/hooks/useValidateMethod';
	import { getRelatedName, getDictName,getDictSelectList, getDictSelect,getWeightUnits } from '../components/RelatedName.js';
	import Enjoy from "@/common/enjoy";
	import { calcAtInByPt,calcAetInByPet,calculatePackages, round,validateOddLot } from '@/hooks/useCalculateMethod';
	import {onLoad} from "@dcloudio/uni-app";
  import {getRdsSysConfig, init} from '@/hooks/init';
	import useService from '@/hooks/useService';
	const service = useService({ prefix: "scApi" });
	
	const mainStore = useMainStore();
	const LoginStore = useLoginStore();
	const EuiNavBar = ref(null);
	const RdsSearchBar = ref(null);
	const searchText = ref('');
	const sUserStore = ref('');
	const sUserStoreName = ref('');
	const sUser = ref('');
	const mainData = ref({});
	const c_id = ref('');
	const c_status =ref('3'); //审核状态
	const c_d_status = ref('1');//发货状态
	const detailData =ref([]);
	const c_sku_total = ref(0);
    const c_n_total = ref(0);
    const c_n_free_total = ref(0);
	const showBasic = ref(true);
	const showRightStyle = ref('text-align: right');
	const currentGds = ref({});
	const oldCurrentGds = ref('');
	const currentGdsIndex = ref(0);
  const sysConfig = ref({
    inputType: '1' // 1-件数零数分别录入方式 2-自动识别含量单值录入方式
  })
	const indexItems = ref([
		{
			label: "配送中心",
			prop: "c_out_store_name",
			type: "text",
			colSpan: 24,
			element: {
			},
		},
		{
			label: "部门",
			prop: "c_out_ad_name",
			type: "text",
			colSpan: 12,
			element: {
			},
		},
		{
			label: "仓库",
			prop: "c_out_wno_name",
			type: "text",
			colSpan: 12,
			element: {
			},
		},
		{
			label: "金额",
			prop: "c_at_move_out",
			type: "text",
			colSpan: 12,
			element: {
				precision: 2
			},
		},
		{
			label: "总数量(含赠品)",
			prop: "c_n_out",
			type: "text",
			colSpan: 12,
			element: {
				precision: 0
			},
		},
		{
			label: "品种数(含赠品)",
			prop: "c_sku_out",
			type: "text",
			colSpan: 12,
			element: {
				precision: 0
			},
		},
		{
			label: "已收正品数量",
			prop: "c_n_total",
			type: "text",
			colSpan: 12,
			element: {
				precision: 0
			},
		},
		{
			label: "已收品种数",
			prop: "c_sku_total",
			type: "text",
			colSpan: 12,
			element: {
				precision: 0
			},
		},
		{
			label: "已收赠品数量",
			prop: "c_n_free_total",
			type: "text",
			colSpan: 12,
			element: {
				precision: 0
			},
		},
		
	])
	const dataGoodsItems = ref(null);
	const popupGoodsItems = ref(null);
	const gdsPopup = ref(null);
	
	onLoad(async (option) => {
    await init();
    await getSysConfig();
		sUserStore.value = option.storeId;
		sUserStoreName.value = getRelatedName('rdsStores', option.storeId);
		mainData.value.c_in_store_id = sUserStore.value;
		if (option.c_id) {
			  c_id.value = option.c_id;
			  billList();
		}
	})

  const getSysConfig = async () => {
    sysConfig.value.inputType = await getRdsSysConfig("供应链管理参数", "商品件数零数录入方式") || '1';
    // 获取参数之后定义
    dataGoodsItems.value = [
      ...[
        {
          label: "条码",
          prop: "c_barcode",
          type: "text",
          colSpan: 24,
          element: {},
        },
        {
          label: "含量/单位",
          prop: "c_unitinfo",
          type: "text",
          colSpan: 12,
          element: {},
        },
        {
          label: "发货数量",
          prop: "c_n_out",
          type: "text",
          colSpan: 12,
          element: {
            precision: 0
          },
        },
        {
          label: "赠品数量",
          prop: "c_n_free_out",
          type: "text",
          colSpan: 12,
          element: {
            precision: 2
          },
        },
        {
          label: "配送价",
          prop: "c_pt_move_fact",
          type: "text",
          colSpan: 12,
          element: {
            precision: 2
          },
        },
        {
          label: "配送金额",
          prop: "c_at_move_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 2
          },
        },
      ],
      ...sysConfig.value.inputType == '1' ? [
        {
          label: "收货件数",
          prop: "c_n_pack_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 0
          },
        },
        {
          label: "收货零数",
          prop: "c_n_odd_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 3
          },
        },
      ] : [
        {
          label: "收货包装数",
          prop: "c_n_input_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 3
          },
        },
      ],
      ...[
        {
          label: "收货数量",
          prop: "c_n_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 0
          },
        },
        {
          label: "赠品数量",
          prop: "c_n_free_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 0
          },
        },
      ]
    ];

    popupGoodsItems.value = [
      ...[
        {
          label: "条码",
          prop: "c_barcode",
          type: "text",
          colSpan: 12,
          element: {},
        },
        {
          label: "含量/单位",
          prop: "c_unitinfo",
          type: "text",
          colSpan: 12,
          element: {},
        },
        {
          label: "发货数量",
          prop: "c_n_out",
          type: "text",
          colSpan: 12,
          element: {
            precision: 0
          },
        },
        {
          label: "赠品数量",
          prop: "c_n_free_out",
          type: "text",
          colSpan: 12,
          element: {
            precision: 2
          },
        },
        {
          label: "配送价",
          prop: "c_pt_move_fact",
          type: "text",
          colSpan: 12,
          element: {
            precision: 2
          },
        },
        {
          label: "配送金额",
          prop: "c_at_move_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 2
          },
        },
      ],
      ...sysConfig.value.inputType == '1' ? [
        {
          label: "收货件数",
          prop: "c_n_pack_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 0
          },
        },
        {
          label: "收货零数",
          prop: "c_n_odd_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 3
          },
        },
      ] : [
        {
          label: "收货包装数",
          prop: "c_n_input_in",
          type: "text",
          colSpan: 12,
          element: {
            precision: 3
          },
        },
      ]
    ];
  }

	const changeBasicStatus = () => {
	  showBasic.value = !showBasic.value;
	}
	const containsLetters = (str) => {
	    return /[a-zA-Z]/.test(str);
	}
	const dataListClass = (item) =>{
		// 从 detailData 查找当前扫描到的商品是否存在
		// if (item.c_barcode == this.currentGds?.c_barcode) {
		// 	return `rds-count-input-content with-current-gds`;
		// } else {
		// 	return `rds-count-input-content`;
		// }
	}
	const leftIconClick = async()=>{
		const serialInfo = {
			gcode: searchText.value,
			serialNo: '',
			sda: null,
			eda: null
		};
		const valSerialRes = await service.request('Rds公共服务', 'ValiSerialNoRule', { storeId: sUserStore.value, serialNo: searchText.value });
		if (valSerialRes.HasException) {
			uni.showToast({
				duration: 2000,
				icon: 'none',
				title: valSerialRes.Exception.Message,
				mask: true,
			});
			return;
		}
		else {
			if (valSerialRes.ObjectData?.isMatchRule) {
				searchText.value = valSerialRes.ObjectData.gcode;
				serialInfo.gcode = valSerialRes.ObjectData.gcode;
				serialInfo.serialNo = searchText.value;
				serialInfo.sda = valSerialRes.ObjectData.sda;
				serialInfo.eda = valSerialRes.ObjectData.eda;
			}
		}
		
		let strlength = searchText.value.length;
		//判断是否包含英文
		const falg = containsLetters(searchText.value);
		if (falg && strlength >= 13) {
			c_id.value = searchText.value;
			uni.showLoading({ title: "正在加载...", mask: true })
			await billQuery();
			uni.hideLoading();
		} else {
			//c_id不为空时，扫描商品
			if (c_id.value) {
				const itemIndex = detailData.value.findIndex(x => x.c_gcode === searchText.value || x.c_barcode === searchText.value);
				if (itemIndex !== -1) {
					const item = detailData.value[itemIndex];
					currentGds.value = item;
					if (mainData.value.c_d_status == '3') {
						return;
					}
					const recNum = Number(item.c_n_in) + Number(item.c_move_pack);
					if (recNum > item.c_n_out) {
						uni.showToast({
							duration: 2000,
							icon: 'none',
							title: `收货数量不能大于发货数量${item.c_n_out}!`,
							mask: true,
						});
					} else {
						item.c_n_in = recNum;
						const result2 = await calculatePackages(item.c_move_pack, recNum);
						item.c_n_pack_in = result2.npack;
						item.c_n_odd_in = result2.odd;
						calcRowAmount(item);
						detailData.value[itemIndex] = item; // 更新原数据
						// return true;
					}
					// setTimeout(() => {
					// 	RdsSearchBar.value.clearIcon();
					// }, 300);
				} else {
					// TODO:如果缓存数据不存在，调用服务验证商品是否存在
					uni.showToast({
						duration: 2000,
						icon: 'none',
						title: `单据不存在此商品[${searchText.value}]！`,
						mask: true,
					});
				}
				// TODO: 保存本地持久化缓存
			} else {
				await billListByGcode(searchText.value);
			}
		}
	}
	//搜索
	const searchConfirm = async(e)=>{
		 searchText.value = e.value;
		if (!searchText.value) {
			return;
		}

		const serialInfo = {
			gcode: searchText.value,
			serialNo: '',
			sda: null,
			eda: null
		};
		const valSerialRes = await service.request('Rds公共服务', 'ValiSerialNoRule', { storeId: sUserStore.value, serialNo: searchText.value });
		if (valSerialRes.HasException) {
			uni.showToast({
				duration: 2000,
				icon: 'none',
				title: valSerialRes.Exception.Message,
				mask: true,
			});
			return;
		}
		else {
			if (valSerialRes.ObjectData?.isMatchRule) {
				searchText.value = valSerialRes.ObjectData.gcode;
				serialInfo.gcode = valSerialRes.ObjectData.gcode;
				serialInfo.serialNo = searchText.value;
				serialInfo.sda = valSerialRes.ObjectData.sda;
				serialInfo.eda = valSerialRes.ObjectData.eda;
			}
		}

		let strlength = searchText.value.length;
		//判断是否包含英文
		const falg = containsLetters(searchText.value);
		if (falg && strlength >= 13) {
			c_id.value = searchText.value;
			uni.showLoading({ title: "正在加载...", mask: true })
			await billQuery();
			uni.hideLoading();
		} else {
			//c_id不为空时，扫描商品
			if (c_id.value) {
				const itemIndex = detailData.value.findIndex(x => x.c_gcode === e.value || x.c_barcode === e.value);
				if (itemIndex !== -1) {
					const item = detailData.value[itemIndex];
					currentGds.value = item;
					if (mainData.value.c_d_status == '3') {
						return;
					}
					const recNum = Number(item.c_n_in) + Number(item.c_move_pack);
					if (recNum > item.c_n_out) {
						uni.showToast({
							duration: 2000,
							icon: 'none',
							title: `收货数量不能大于发货数量${item.c_n_out}!`,
							mask: true,
						});
					} else {
						item.c_n_in = recNum;
						const result2 = await calculatePackages(item.c_move_pack, recNum);
						item.c_n_pack_in = result2.npack;
						item.c_n_odd_in = result2.odd;
						calcRowAmount(item);
						detailData.value[itemIndex] = item; // 更新原数据
						// return true;
					}
					// setTimeout(() => {
					// 	RdsSearchBar.value.clearIcon();
					// }, 300);
				} else {
					// TODO:如果缓存数据不存在，调用服务验证商品是否存在
					uni.showToast({
						duration: 2000,
						icon: 'none',
						title: `单据不存在此商品[${e.value}]！`,
						mask: true,
					});
				}
				// TODO: 保存本地持久化缓存
			} else {
				await billListByGcode(searchText.value);
			}
		}
	}
	//选择框点击事件
   const clickRight = (selectType) =>{
		// 选择订单
		uni.navigateTo({
			url: './omOrder/index?storeId=' + mainData.value.c_in_store_id
		});
   }
   
   const onClickGdsInfo = (item, index) => {
		if (mainData.value.c_d_status == '3') {
			return;
		}
		currentGdsIndex.value = index;
		currentGds.value = JSON.parse(JSON.stringify(item));
		oldCurrentGds.value = JSON.stringify(item);
		gdsPopup.value.open('bottom');
   }
   
  const validateDetail = async(args) => {
		const { type, fieldName, oldValue, newValue, itemIndex } = args;
		const weightUnits = await getWeightUnits();
		switch (fieldName) {
			case 'c_n_in':
				const recN = newValue;
				currentGds.value.c_n_in = recN;

				if (!weightUnits.includes(currentGds.value.c_move_unit)) {
					if (recN % 1 > 0) {
						uni.showToast({
							duration: 2000,
							icon: 'none',
							title: '本商品验收数量不允许录入小数，仅重量单位商品可以录入小数'
						});
						const oldData = JSON.parse(oldCurrentGds.value);
						currentGds.value.c_n_in = oldData.c_n_in;
						return false;
					}
				}
				if (recN > currentGds.value.c_n_out) {
					uni.showToast({
						duration: 2000,
						icon: 'none',
						title: `收货数量${recN}不能大于发货数量${currentGds.value.c_n_out}`
					});
					const oldData = JSON.parse(oldCurrentGds.value);
					currentGds.value.c_n_in = oldData.c_n_in;
					return false;
				}
				const valResult = validateOddLot(newValue, currentGds.value.c_n_pack_in ?? 0, currentGds.value.c_move_pack, '1');
				let result = valResult.result;
				if (!result || result?.validated) {
					currentGds.value.c_n_pack_in = valResult.npack;
					currentGds.value.c_n_odd_in = newValue % currentGds.value.c_move_pack;
                    currentGds.value.c_n_input_in = round(newValue / currentGds.value.c_move_pack, 3);

					//收货配送金额
					currentGds.value.c_at_move_in = calcAtInByPt({ c_pt: currentGds.value.c_pt_move_fact, c_n: newValue });
					//收货不含税配送金额
					currentGds.value.c_aet_move_in = await calcAetInByPet({ c_pet: currentGds.value.c_pet_move_fact, c_n: newValue });
					mainData.value.c_n_in += (newValue ?? 0 - oldValue ?? 0)
					mainData.value.c_at_move_in = detailData.value.reduce((pre, current) => pre + current.c_at_move_in, 0);
					mainData.value.c_aet_move_in = detailData.value.reduce((pre, current) => pre + current.c_aet_move_in, 0);
				} else {
                    uni.showToast({
                        duration: 2000,
                        icon: 'none',
                        title: result?.message
                    });
                    return false;
				}
				break;
			case 'c_n_free_in':
				const recFee = newValue;
				currentGds.value.c_n_free_in = recFee;
				if (!weightUnits.includes(currentGds.value.c_move_unit)) {
					if (recFee % 1 > 0) {
						uni.showToast({
							duration: 2000,
							icon: 'none',
							title: '本商品赠品数量不允许录入小数，仅重量单位商品可以录入小数'
						});
						const oldData = JSON.parse(oldCurrentGds.value);
						currentGds.value.c_n_free_in = oldData.c_n_free_in;
						return false;
					   
					}
				}
				if (recFee > currentGds.value.c_n_free_out) {
					uni.showToast({
						duration: 2000,
						icon: 'none',
						title: `赠品确认收货数量不可大于赠品发货数量`
					});
					const oldData = JSON.parse(oldCurrentGds.value);
					currentGds.value.c_n_free_in = oldData.c_n_free_in;
					return false;
				}
				mainData.value.c_n_in += (recFee??0 - oldValue??0);
				break;
		}
	}
  // 保存
  const saveClick = async() =>{
	   // 保存
	  if (!mainData.value.c_id) {
		  uni.showToast({
			  duration: 2000,
			  icon: 'none',
			  title: '订单号不能为空！'
		  });
		  return false;
	  }
	  if (!mainData.value.c_in_store_id) {
		  uni.showToast({
			  duration: 2000,
			  icon: 'none',
			  title: '机构不能为空！'
		  });
		  return false;
	  }
	  uni.showLoading({ title: "正在保存...", mask: true })
	  await saveOmBill();
	  uni.showToast({
	  	duration: 2000,
	  	icon: 'none',
	  	title: `保存成功`
	  });
	  uni.hideLoading(); 
  }
   // 收货确认
  const receiptClick = async() =>{
	   // 收货确认
	  if (!mainData.value.c_id) {
		  uni.showToast({
			  duration: 2000,
			  icon: 'none',
			  title: '订单号不能为空！'
		  });
		  return false;
	  }
	  if (!mainData.value.c_in_store_id) {
		  uni.showToast({
			  duration: 2000,
			  icon: 'none',
			  title: '机构不能为空！'
		  });
		  return false;
	  }
	  await recConfirm();
  }
  
  const cancelClick = ()=>{
	  gdsPopup.value.close();
  }
  const submitClick = ()=>{
	  uni.showLoading({ title: "正在加载...", mask: true })
	  currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
	  detailData.value[currentGdsIndex.value] = currentGds.value;
	  gdsPopup.value.close();
	  calcMainAmount();
	  uni.hideLoading();
  }
  // 获取单据列表信息
  const billList = async () =>{
  		uni.showLoading({ title: "正在加载...", mask: true })
  		const req = {
  			WhereList: [
  				{ c_col: "c_id", c_oper: "等于", c_value: c_id.value, c_logic: "而且" },
  				{ c_col: "c_status", c_oper: "等于", c_value: c_status.value, c_logic: "而且" },
  				{ c_col: "c_in_store_id", c_oper: "等于", c_value: mainData.value.c_in_store_id, c_logic: "而且" },
  			]
  		};
  		const result = await service.request('商品配送单', 'EnjoyQueryList', req,'801');
  		uni.hideLoading();
  		const _data = result.ReturnObject.map(x=>{
			return{
				...x,
				c_out_store_name:`[${x.c_out_store_id}]${getRelatedName('rdsStores', x.c_out_store_id)||''}`,
				c_out_ad_name:`[${x.c_out_adno}]${getRelatedName('rdsDeparts', x.c_out_adno)||''}`,
				c_out_wno_name:`[${x.c_out_wno}]${getRelatedName('rdsWnos', x.c_out_wno)||''}`,
			}
		});
  		if (_data.length > 0) {
  			mainData.value = _data[0];
  			c_id.value = mainData.value.c_id;
  			await billQuery();
  		} else {
  			uni.showToast({
  				duration: 2000,
  				icon: 'none',
  				title: '未查询到配送单',
  				mask: true,
  			});
  			mainData.value = {};
  			detailData.value = [];
  		   
  		}
  		
  	}
  	// 获取配送单单据列表信息
  	const billListByGcode = async (gcode) => {
  		uni.showLoading({ title: "正在加载...", mask: true });
  		const req = {
  			WhereList: [
  				{ c_col: "c_gcode", c_oper: "等于", c_value: gcode, c_logic: "而且" },
  				{ c_col: "c_in_store_id", c_oper: "等于", c_value: mainData.value.c_in_store_id, c_logic: "而且" },
  				{ c_col: "c_status", c_oper: "等于", c_value: c_status.value, c_logic: "而且" },
  				{ c_col: "c_d_status", c_oper: "等于", c_value: c_d_status.value, c_logic: "而且" },
  				// { c_col: "c_summary", c_oper: "包含", c_value: this.c_summary, c_logic: "而且" },
  			]
  		};
  		if (c_id.value) {
  			req.ObjectData.WhereList.push({
  				c_col: "c_id",
  				c_oper: "等于",
  				c_value: c_id.value,
  				c_logic: "而且",
  			});
  		}
  		const result = await service.request('商品配送单', 'EnjoyQueryList', req,'801');
  	   uni.hideLoading();
  		var _data = result.ReturnObject;
  		if (_data.length == 1) {
  			mainData.value = _data[0];
  			c_id.value = mainData.value.c_id;
  			await billQuery();
  		} else if (_data.length > 1) {
  			if (!c_id.value) {
  				uni.navigateTo({
  					url: './modals/omOrder/index?storeId=' + mainData.value.c_in_store_id + "&orderData=" + JSON.stringify(_data)
  				});
  			}
  		} else {
  			uni.showToast({
  				duration: 2000,
  				icon: 'none',
  				title: '未查询到配送单',
  				mask: true,
  			});
  			// setTimeout(() => {
  			// 	RdsSearchBar.value.clearIcon();
  			// }, 300);
  		}
  	}
  	const billQuery = async() => {
  		if (!c_id.value) {
  			return;
  		}
  		const req = {
  			BillId: c_id.value,
  		};
  		const result = await service.request('商品配送单', 'EnjoyBillQuery', req,'801');
  		const _data = result.ds.map(x=>{
  			return{
  				...x,
  				c_out_store_name:`[${x.c_out_store_id}]${getRelatedName('rdsStores', x.c_out_store_id)||''}`,
  				c_out_ad_name:`[${x.c_out_adno}]${getRelatedName('rdsDeparts', x.c_out_adno)||''}`,
  				c_out_wno_name:`[${x.c_out_wno}]${getRelatedName('rdsWnos', x.c_out_wno)||''}`,
  			}
  		});
		if (result.ds.length > 0) {
  			mainData.value = _data[0];
  			detailData.value = result.ds1.map(x=>{
  				return {
  					...x,
  					c_unitinfo:x.c_move_pack + '/' + x.c_move_unit,
  				}
  			});
  			c_sku_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n_in > 0 || current.c_n_free_in > 0), 0);
  			c_n_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n_in ?? 0), 0);
  			c_n_free_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n_free_in ?? 0), 0);
  		} else {
  			uni.showToast({
  				duration: 2000,
  				icon: 'none',
  				title: '未查询到数据',
  				mask: true,
  			});
  		  
  		}
  	}
	// 保存数据
	const saveOmBill = async() => {
		 const list = detailData.value
		for (let i = 0; i < list.length; i++) {
			const item = list[i];
			if(!item.c_n_in)
			{
				item.c_n_in = 0; 
			}
			if(!item.c_n_free_in)
			{
				item.c_n_free_in = 0;   
			}
		}
		var childModel = {
			NewList: [],
			ModifiedList: detailData.value,
			DelList: [],
			TableName: 'tb_io_om_g',
			PrimaryKeys: ['c_tenant_id', 'c_id', 'c_gsort']
		};
		const req = {
			NewList: [],
			ModifiedList: [mainData.value],
			DelList: [],
			TableName: 'tb_io_om',
			PrimaryKeys: ['c_tenant_id', 'c_id'],
			ChildData: [{
			    ChildTableName: 'tb_io_om_g',
			    ParentTableName: 'tb_io_om',
			    ChildColumnNames: ['c_id'],
			    ParentColumnNames: ['c_id'],
			    ChildSaveModel: childModel
			}],
			BillSet: {
			    BillIdKeyValue: {
			        key: 'c_id',
			        value: mainData.value.c_id
			    },
			    BillVariable: "",
			    TableName: 'tb_io_om'
			}
		};
		const result = await service.request('配送收货确认', 'SaveOmBill', req);
	}
	//收货确认
	const recConfirm = async() =>{
		uni.showModal({
			title: ' 提示',
			content: '确定收货吗?',
			showCancel: true,
			success: async (res) => {
				if (res.confirm) {
					uni.showLoading({ title: "正在收货确认,请稍后...", mask: true })
					await saveOmBill();
					const result = await service.request('配送收货确认', 'ConfirmOperate', { billId: mainData.value.c_id, billType: mainData.value.c_bill_type });
					uni.hideLoading();
					console.log('resultresult',result)
					uni.showToast({
						duration: 2000,
						icon: 'none',
						title: '收货确认成功！'
					});
					await billQuery();
				}
			}
		});
	}
   /**
	* 计算当前金额
	*/
    const calcRowAmount = (param) =>{
		//收货配送金额
		param.c_at_move_in = calcAtInByPt({ c_pt: param.c_pt_move_fact, c_n: param.c_n_in });
		//收货不含税配送金额
		param.c_aet_move_in = calcAtInByPt({ c_pt: param.c_pet_move_fact, c_n: param.c_n_in });
		// this.calcMainAmount();
	}
	
	const calcMainAmount = () => {
		mainData.value.c_n_in = detailData.value.reduce((pre, current) => pre + (current.c_n_in ?? 0) + (current.c_n_free_in ?? 0), 0);
		mainData.value.c_at_move_in = detailData.value.reduce((pre, current) => pre + current.c_at_move_in, 0);
		mainData.value.c_aet_move_in = detailData.value.reduce((pre, current) => pre + current.c_aet_move_in, 0);
		c_sku_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n_in > 0 || current.c_n_free_in > 0), 0);
		c_n_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n_in ?? 0), 0);
		c_n_free_total.value = detailData.value.reduce((pre, current) => pre + (current.c_n_free_in ?? 0), 0);
	};
	 
	const SelectionChanged = async(item) => {
	    c_id.value = item;
	    await billQuery();
	}
	// 录入列表的相同商品的index
	const sameGdsIndex = (item) => {
		if (item) {
			return detailData.value.findIndex(i => i.c_barcode == item?.c_barcode);
		}
	}	
	defineExpose({
		SelectionChanged
	})
</script>

<style lang="scss" scoped>
	@import '../../../main.scss';

	.content {
		display: flex;
		flex: 1;
		flex-direction: column;
		background-color: #F2F2F2;
		padding: 0px !important
	}

	.content-img {
		background-color: #FFFFFF;
		background-size: 100% 176rpx;
		background-repeat: no-repeat;
		width: 100%;
	}

	.navigation {
		flex: 0 0 auto;
		margin-bottom: 5px;
	}

	.top-view {
		width: 100%;
		height: 88rpx;
		background: #FFFFFF;
	}

	.main-view {
		flex: 1;
		flex-direction: column;
	}

	.search-fields {
		width: 100%;
		background: #FFFFFF;
		position: relative;

		.bottom {
			background: #ffffff;
			border-top: 1rpx solid $uni-line-color;
			display: flex;
			justify-content: center;
			padding: 20rpx;
		}
	}

	.top-view {
		width: 100%;
		height: 88rpx;
	}

	.extra-view {
		margin-right: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 60rpx;
		height: 100%;
	}

	.footer-view {
		width: 100%;
		flex: 1;
	}

	.list-scroll {
		width: 100%;
		height: 300rpx;
		box-sizing: border-box;
	}

	.bottom-view {
		width: 100%;
		height: 100rpx;
		background: #FFFFFF;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		flex-direction: row;
	}

	.center-style {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		margin-right: 20rpx;
		gap: 20rpx;
	}

	//内容行
	.item-view {
		display: flex;
		flex-wrap: wrap;
		flex-direction: row;
		align-items: center;
		margin-top: 16rpx;
		row-gap: 8rpx;
	}

	.line-view {
		width: 100%;
		height: 1rpx;
		background: #EEEEEE;
		margin: 20rpx 0;
	}

	.fab-view {
		width: 60rpx;
		height: 100%;
		//background: #00aaff;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	.popup-content {
		align-items: center;
		justify-content: flex-start;
		flex-direction: column;
		padding: 0 20rpx 20rpx 20rpx;
		background-color: #ffffff;
		border-radius: 20rpx 20rpx 0 0;
	}

	.popup-title {
		width: 100%;
		height: 84rpx;
		background: #FFFFFF;
		border-radius: 40rpx 40rpx 0 0;
		display: flex;
		justify-content: center;
		align-items: center;
		color: $uni-text-color-secondary;
		font-size: $uni-font-size-level1;
		line-height: 45rpx;
		font-weight: 600;
		text-align: center;
		position: relative;
	}

	.popup-content-message {
		align-items: center;
		justify-content: left;
		flex-direction: column;
		padding: 0 20rpx 20rpx 20rpx;
		width: 600rpx;
		background-color: #ffffff;
		border-radius: 20rpx 20rpx 0 0;
	}

	.popup-title {
		width: 100%;
		height: 84rpx;
		background: #FFFFFF;
		border-radius: 40rpx 40rpx 0 0;
		display: flex;
		justify-content: center;
		align-items: center;
		color: $uni-text-color-secondary;
		font-size: $uni-font-size-level1;
		line-height: 45rpx;
		text-align: center;
		position: relative;
	}

	.m-list-top {
		display: grid;
		grid-template-columns: 50% 50%;
		padding: 0 0 16rpx;
		border-bottom: 2px solid #c8c7cc;
		font-size: 24rpx;
	}

	.popup-bottom {
		background: #ffffff;
		border-top: 1rpx solid $uni-line-color;
		display: flex;
		justify-content: center;
		padding: 20rpx;
	}

	::v-deep .e-card {
		margin-left: 0rpx !important;
		margin-right: 0rpx !important;
	}

	::v-deep .e-card__content {
		margin-left: 0rpx !important;
		margin-right: 0rpx !important;
	}

	::v-deep .list_cell {
		width: 100% !important;
		margin: 0 !important;
	}

	.bottom {
		height: 70rpx;
		display: flow-root;
		text-align: center;
		border-bottom-left-radius: $uni-border-radius-lg;
		border-bottom-right-radius: $uni-border-radius-lg;
		padding: $uni-spacing-col-sm*2 $uni-spacing-row-sm;
		background: $uni-bg-color;
		text-align: right;
	}

	.bt-button {
		background-color: #FFFFFF;
		padding: 10rpx 0rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}

	::v-deep .m-card-input-title {
		text-align: left;
	}

	::v-deep .m-card-input-view {
		padding: 24rpx 0rpx 16rpx !important;
	}

	.item-gds-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
</style>